package com.nstar.base.controls
{
	import com.nstar.base.util.Logger;
	import com.nstar.base.util.StringUtils;
	import com.nstar.base.util.SystemUtils;
	
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.utils.clearInterval;
	import flash.utils.setInterval;
	
	import mx.containers.Canvas;
	import mx.core.Application;
	import mx.managers.PopUpManager;
	import mx.modules.ModuleLoader;
	
	/**
	 * 
	 * 	屏保监控器
	 * 
	 * 	开启屏幕保护监控功能，在指定的时间内如果鼠标没有移动，则调用屏保程序并关闭鼠标监控功能
	 * 	屏保程序在关闭时要往本地ShareObject中写个closed标志，可在屏幕单击事件后写入这个标志
	 * 	这样监控屏保的程序在检查到这个状态后就重新开启屏保监控功能
	 * 
	 * 	鼠标没有移动只是大致的算法，检查鼠标在X和Y方向上移动不超过一定距离(很小，如2两个像素)则认为是没动
	 * 
	 * 	@author:zhucm
	 * 	@date:2007.10.10
	 */ 
	
	public class ScreenSaverListener
	{
		private var intervalId:int;//鼠标监控返回
		private var ssIntervalId:int;//屏保监控返回
		private var oldx:int = 0;	//鼠标旧的位置
		private var oldy:int = 0;
		
		[Bindable]
		public var waitSeconds:int = 1;//从鼠标未移动开始计算等待时间
		
		//屏保出现的时间，单位为秒
		private var _timeout:int = 5;
		//屏保程序名称
		private var screensaver:*;
		private var screensaverUrl:String;
		
		private var CLOSED:String = "closed";
		private const ONE_SECOND:int = 1000;
		//是否启用屏保监听器
		private var _enabled:Boolean = true;
		
		private var app:* = Application.application;
		private var cavProxy:Canvas = new Canvas();
		
		public var distance:int = 3;
		
		private var logger:Logger = Logger.getInstance();

		public function ScreenSaverListener(screensaverUrl:String,timeout:int = 5){
			this.screensaverUrl = screensaverUrl;
			this._timeout = timeout;
			
		}
		
		public function set enabled(value:Boolean):void{
			this._enabled = value;
			
			if (!_enabled){
				clearInterval(intervalId);
				clearInterval(ssIntervalId);
				logger.debug("screensaver is disabled!");
			}else{
				intervalId = setInterval(mouseListener,ONE_SECOND);
			}
			
		}
		public function get enabled():Boolean{
			return this._enabled;
		}
		
		//设置超时
		public function set timeout(value:int):void{
			enabled = false;
			this._timeout = value;
			enabled = true;
		}
		
		//转到屏保程序
		private function loadScreenSaver():void{
			logger.debug("load screensaver...");
			SystemUtils.setMemory("screensaver",CLOSED,"false");//初始化为false
			//清除定时器
			clearInterval(intervalId);
			/*
			if (screensaverUrl!=null && screensaverUrl!=""){
				navigateToURL(new URLRequest(screensaverUrl),"_self" );	
			}*/
			initCanvasProxy();
	        loadSampleScreenSaver();				
		}
		
		private function initCanvasProxy():void{
			if (cavProxy == null){
				cavProxy = new Canvas();
			}
			cavProxy.x = 0;
			cavProxy.y = 0 ;
			cavProxy.width = app.stage.width;
			cavProxy.height = app.stage.height; 
			cavProxy.setStyle("backgroundColor",0xFFFFFF);
			cavProxy.setStyle("backgroundAlpha",0.618);
			cavProxy.addEventListener(MouseEvent.CLICK,closeHandler);
			//cavProxy.addEventListener(KeyboardEvent.KEY_DOWN,closeHandler);
			if (!StringUtils.isEmpty(screensaverUrl)){
				//使用ModuleLoader 加载屏保程序
				logger.debug("load screensaver....************");
				var ml:ModuleLoader = new ModuleLoader();
				ml.url = screensaverUrl;
				cavProxy.addChild(ml);
				/*
				var loader:Loader = new Loader();
				loader.load(new URLRequest(screensaverUrl));
				cavProxy.removeAllChildren();
				cavProxy.addChild(loader);
				*/
			}

		}
		
		//加载示例屏幕保护程序
		private function loadSampleScreenSaver():void{
			PopUpManager.addPopUp(cavProxy,app);
			PopUpManager.centerPopUp(cavProxy);
		}
		
		private function closeHandler(event:*):void{
			login = PopUpManager.createPopUp(cavProxy,Login,true) as Login;
			PopUpManager.centerPopUp(login);
			login.addEventListener("OK",okHandler);
		}
		
		private function okHandler(event:Event):void{
			SystemUtils.setMemory("screensaver",CLOSED,"true");
			if (login!=null){
				PopUpManager.removePopUp(login);
			}
			if (cavProxy!=null){
				cavProxy.removeAllChildren();
				PopUpManager.removePopUp(cavProxy);
			}
			logger.debug("screesaver has been removed!");
		}
		
		//鼠标监控
		private function mouseListener():void{
			logger.debug("listening...");
			
			if (waitSeconds >= _timeout ){
				//恢复计时
				waitSeconds = 1;
				//转到屏幕保护程序
				loadScreenSaver();
				//打开监控屏幕保护监控程序，如果屏保程序已经关闭，则启动定时器
				ssIntervalId = setInterval(screensaverListener,ONE_SECOND);
				return;
			}
			//鼠标移动范围小于3时认为鼠标没有移动
			if (Math.abs(oldx - Application.application.mouseX)<distance && 
				Math.abs(oldy - Application.application.mouseY)<distance){
				waitSeconds ++;
			}else{
				if (oldx !=0 && oldy !=0){
					logger.debug("mouse moved, listen again...");	
				}
				
				waitSeconds = 1;
			}
			//保存鼠标原有的位置
			oldx = Application.application.mouseX;
			oldy = Application.application.mouseY;
		}
		
		//监控屏保程序是否已经关闭，通过查看shareObject对象中保存的数据来检查
		private function screensaverListener():void{
			
			var closed:String = SystemUtils.getMemory("screensaver",CLOSED);
			if (closed!=null && closed=="true"){
				//关闭屏保监听器
				clearInterval(ssIntervalId);
				//重写数据
				SystemUtils.setMemory("screensaver",CLOSED,"false");
				//重新打开鼠标监听器
				oldx = 0;
				oldy = 0;
				intervalId = setInterval(mouseListener,1000);
			}
		}	
	}
}